package com.czl.lunt.controller;

import com.czl.lunt.common.Result;
import com.czl.lunt.common.ResultCode;
import com.czl.lunt.config.AppConfig;
import com.czl.lunt.model.Article;
import com.czl.lunt.model.ArticleReply;
import com.czl.lunt.model.User;
import com.czl.lunt.service.ArticleReplyService;
import com.czl.lunt.service.ArticleService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/reply")
public class ArticleReplyController {

    @Autowired
    private ArticleService articleService;
    @Autowired
    private ArticleReplyService articleReplyService;

    @PostMapping("/create")
    public Result create (HttpServletRequest request,
                          @RequestParam("articleId") @NonNull Long articleId,
                          @RequestParam("content") @NonNull String content) {
        // 获取用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 判断用户是否已禁言
        if (user.getState() != 0) {
            // 表示已禁言
            return Result.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 获取要回复的帖子对象
        Article article = articleService.selectById(articleId);
        // 是否存在，或已删除

        if (article == null) {
            // 表示已删除或不存在
            return Result.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        // 是否封帖
        if (article.getState() != 0) {
            // 表示已封贴
            return Result.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }

        // 构建回复对象
        ArticleReply articleReply = new ArticleReply();
        articleReply.setArticleId(articleId); // 要回复的帖Id
        articleReply.setPostUserId(user.getId()); // 回复的发送者
        articleReply.setContent(content); // 回复的内容
        // 写入回复
        articleReplyService.create(articleReply);
        // 返回结果
        return Result.success();
    }

    @GetMapping("/getReplies")
    public Result<List<ArticleReply>> getRepliesByArticleId (
            @RequestParam("articleId") @NonNull Long articleId) {
        // 校验帖子是否存在
        Article article = articleService.selectById(articleId);
        // 调用Service
        List<ArticleReply> articleReplies = articleReplyService.selectByArticleId(articleId);
        // 返回结果
        return Result.success(articleReplies);

    }
}
